/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.baseDataView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingWorker;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

import com.ruipengkj.bean.TProductCatalog;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.component.jtree.JTreeCellRenderer;
import com.ruipengkj.component.jtree.OverwriteDefaultMutableTreeNode;
import com.ruipengkj.service.TProductCatalogService;

/**
 * 说明：
 * 商品分类树面板
 * @Author：李智深
 * @Date：2012-03-14
 */
public class DataTProductCatalogTreePanel extends JPanel implements TreeExpansionListener{

	private static final long serialVersionUID = 1L;
	private JTree tree;
	private DefaultTreeModel treeModel = null;
	private TProductCatalogService tProductCatalogService;//产品目录
	
	private DataCommodityQuery dataCommodityQuery;
	
	private JProgressBar jpb;
	
	public DataTProductCatalogTreePanel(JProgressBar jpb, boolean noBorder){
		this.jpb = jpb;
		this.setLayout(new BorderLayout());
		tProductCatalogService=BuildSpringApplication.getInstance().getTProductCatalogServiceImpl();
		
		try {
			List<TProductCatalog> tProductCatalogList = tProductCatalogService.findService(null);
			if(tProductCatalogList != null) 
				jpb.setMaximum(tProductCatalogList.size()+1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		JScrollPane tree_jsp = new JScrollPane();
		treeModel=initTreeModel();
		tree = new JTree(treeModel); // JTree构造方法
		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION );
		tree.setShowsRootHandles(true); // 显示根结点左边的控制手柄
		tree.collapseRow(0);// 初始时只显示根结点
		tree.addTreeExpansionListener(this);
		tree.setCellRenderer(new JTreeCellRenderer());
		tree_jsp.setViewportView(tree);
		this.add(tree_jsp);
	}
	
	public DataTProductCatalogTreePanel(JProgressBar jpb){
		this.jpb = jpb;
		this.setLayout(new BorderLayout());
		tProductCatalogService=BuildSpringApplication.getInstance().getTProductCatalogServiceImpl();
		
		try {
			List<TProductCatalog> tProductCatalogList = tProductCatalogService.findService(null);
			if(tProductCatalogList != null) 
				jpb.setMaximum(tProductCatalogList.size()+1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.initView();
	}
	
	private void initView(){
		JScrollPane tree_jsp = new JScrollPane();
		tree_jsp.setBorder(null);
		treeModel=initTreeModel();
		tree = new JTree(treeModel) {
			private static final long serialVersionUID = 1L;
			private Color color = new Color(246, 163, 49);
			@Override
			protected void paintBorder(Graphics g) {
				g.setColor(color);
				g.fillRect(0, 0, 4, this.getHeight());
				g.fillRect(this.getWidth()-4, 0, 4, this.getHeight());
			}
		}; // JTree构造方法
		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION );
		tree.setShowsRootHandles(true); // 显示根结点左边的控制手柄
		tree.collapseRow(0);// 初始时只显示根结点
		tree.addTreeExpansionListener(this);
		tree.setCellRenderer(new JTreeCellRenderer());
		tree_jsp.setViewportView(tree);
		this.add(tree_jsp);
	}
	
	public void refreshModel() {
		treeModel = initTreeModel();
		tree.setModel(treeModel);
		tree.collapseRow(0);
	}
	/**--------------------------------左边树操作------------------------------------*/
	// 从数据库中读取根结点、并增加“载入中...”子结点
	private DefaultTreeModel initTreeModel() {
		DefaultTreeModel treeModel = null;
			OverwriteDefaultMutableTreeNode root = new OverwriteDefaultMutableTreeNode("", "所有产品", "");
			treeModel = new DefaultTreeModel(root);
			addLoadingNode(treeModel, root);
		return treeModel;
	}

    // 增加“载入中...”子结点的方法
    private void addLoadingNode(DefaultTreeModel treeModel, OverwriteDefaultMutableTreeNode parent) {
    	OverwriteDefaultMutableTreeNode loading = new OverwriteDefaultMutableTreeNode("载入中...");
        treeModel.insertNodeInto(loading, parent, parent.getChildCount());
        
        jpb.setValue(jpb.getValue()+1);
    }
   
    
	// 从数据表中读取expandNode的子结点.返回值为处理时长
	private long asynchLoad(OverwriteDefaultMutableTreeNode expandNode,DefaultTreeModel treeModel) {
		long handleTime = 0L;
		long start = System.currentTimeMillis();
		try {
			List<TProductCatalog> list = tProductCatalogService.findListService(expandNode.getNodeStringID());
			if (list != null && list.size() != 0) {
				for (int i = 0; i < list.size(); i++) {
					TProductCatalog key = list.get(i);
					OverwriteDefaultMutableTreeNode obj = new OverwriteDefaultMutableTreeNode(key.getCatalogID(), key.getName(), key.getDes());
//					if (key.getTProductCatalogs() != null) {
						addLoadingNode(treeModel, obj);
//					}
					treeModel.insertNodeInto(obj, expandNode, expandNode.getChildCount());
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}finally {
			handleTime = System.currentTimeMillis() - start; // 计算出处理时长
		}
		return handleTime;
	}
	
	//展开树
	private void updateTree(final OverwriteDefaultMutableTreeNode expandNode){
		if (!expandNode.isVisited()) {
			expandNode.setVisited(true);
			expandNode.setIsNull(false);
			tree.setEnabled(false);
			new SwingWorker<Long, Void>() {
				@Override
				protected Long doInBackground() throws Exception {
					return asynchLoad(expandNode, treeModel);
				}
				@Override
				protected void done() {
					treeModel.removeNodeFromParent(expandNode.getFirstLeaf());
					treeModel.nodeStructureChanged(expandNode); // 通知视图结构改变
					tree.setEnabled(true);
					if (dataCommodityQuery != null) {
						dataCommodityQuery.queryCommodity();
					}
				}
			}.execute();
		}
	}
	
	@Override
	public void treeExpanded(TreeExpansionEvent event) {
		final OverwriteDefaultMutableTreeNode expandNode = (OverwriteDefaultMutableTreeNode) event.getPath().getLastPathComponent();
		this.updateTree(expandNode);
	}

	@Override
	public void treeCollapsed(TreeExpansionEvent event) {
		// TODO Auto-generated method stub
	}

	public void setDataCommodityQuery(DataCommodityQuery dataCommodityPanel) {
		this.dataCommodityQuery = dataCommodityPanel;
	}
	public JTree getTree() {
		return tree;
	}

	public DefaultTreeModel getTreeModel() {
		return treeModel;
	}
}
